package com.example.restaurant.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.restaurant.common.R;
import com.example.restaurant.dto.ChatDto;
import com.example.restaurant.dto.ChatDto1;
import com.example.restaurant.dto.UserDto;
import com.example.restaurant.entity.Chat;
import com.example.restaurant.entity.User;
import com.example.restaurant.service.ChatService;
import com.example.restaurant.service.UserService;
import com.example.restaurant.utils.JwtUtil;
import io.netty.util.internal.StringUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: chat
 * @BelongsPackage: com.example.restaurant.controller
 * @Author: chenAng
 * @CreateTime: 2023-12-07  21:01
 * @Version: 1.0
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class ChatController {


    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private ChatService chatService;

    @Autowired
    private UserService userService;

    //获取消息页面最后与每个用户的最后一条记录展示到页面
    @RequestMapping ("/chat/getChatList")
    public R<List<ChatDto>> getChatList(HttpServletRequest request){

        String token = request.getHeader("Sessionid");
        User user = jwtUtil.getToken(token);

        List<Chat> list = chatService.getOldChatList(user);

        List<ChatDto> listdto = new ArrayList<>();
        for(Chat list1:list){

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            if (list1.getSendid().equals(String.valueOf(user.getUserid()))){
                queryWrapper.eq(User::getUserid,list1.getReceiverid());
            }else {
                queryWrapper.eq(User::getUserid,list1.getSendid());
            }
            User one = userService.getOne(queryWrapper);

            ChatDto chatDto = new ChatDto();
//            chatDto.setSendid(list1.getSendid());
            chatDto.setReceiverid(String.valueOf(one.getUserid()));
//            chatDto.setUser(one);
            chatDto.setUname(one.getUname());
            chatDto.setAvatar(one.getAvatar());
            chatDto.setMessage(list1.getMessage());
            chatDto.setType(0);
            chatDto.setSendtime(list1.getSendtime());
            chatDto.setIs_read(list1.getIs_read());
            listdto.add(chatDto);
        }
//        System.out.println(listdto);
        return R.success(listdto);
    }
    //获取未读信息数量
    @RequestMapping ("/chat/getNoReadNum")
    public R<String> getNoReadNum(HttpServletRequest request){
        String token = request.getHeader("Sessionid");
        User user = jwtUtil.getToken(token);
        LambdaQueryWrapper<Chat> chatLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chatLambdaQueryWrapper.eq(Chat::getReceiverid,user.getUserid());
        chatLambdaQueryWrapper.eq(Chat::getIs_read,1);
        int count = chatService.count(chatLambdaQueryWrapper);

        if (count == 0){
            return R.success("0");
        }else {
            return R.success(String.valueOf(count));
        }
    }




    //通过用户id查询聊天记录
    @RequestMapping ("/chat/queryPrivateChatByPage")
    public R<List<ChatDto1>> queryPrivateChatByPage(@Param("toUserId") Integer toUserId, Integer offset, Integer limit, HttpServletRequest request){
        String token = request.getHeader("Sessionid");
        User user = jwtUtil.getToken(token);
        //分页构造器
        Page<Chat> pageInfo = new Page<>(offset,limit);
        LambdaQueryWrapper<Chat> chatLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chatLambdaQueryWrapper.eq(Chat::getSendid, user.getUserid())
                .eq(Chat::getReceiverid, toUserId)
                .or()
                .eq(Chat::getSendid, toUserId)
                .eq(Chat::getReceiverid, user.getUserid())
                .orderByAsc(Chat::getSendtime);

        Page<Chat> page = chatService.page(pageInfo, chatLambdaQueryWrapper);

        List<Chat> records = page.getRecords();
        //构建前端所需要的返回参数
        List<ChatDto1> newRecords = new ArrayList<>();

        for (Chat record : records) {
            ChatDto1 chatDto1 = new ChatDto1();
            chatDto1.setId(record.getId());
            chatDto1.setSendtime(record.getSendtime());
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserid,record.getSendid());
            User sendUser = userService.getOne(queryWrapper);
            chatDto1.setUser(sendUser);
            chatDto1.setMessage(record.getMessage());
            newRecords.add(chatDto1);
        }
//        System.out.println(newRecords);
//        page.setRecords(newRecords)

        return R.success(newRecords);
    }


    @RequestMapping ("/chat/readMsg")
    public R<List<ChatDto1>> readMsg(@Param("toUserId") Integer toUserId, HttpServletRequest request){
        String token = request.getHeader("Sessionid");
        User user = jwtUtil.getToken(token);


        LambdaQueryWrapper<Chat> chatLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chatLambdaQueryWrapper.eq(Chat::getSendid, user.getUserid())
                .eq(Chat::getReceiverid, toUserId)
                .or()
                .eq(Chat::getSendid, toUserId)
                .eq(Chat::getReceiverid, user.getUserid())
                .orderByAsc(Chat::getSendtime);
        List<Chat> list = chatService.list(chatLambdaQueryWrapper);

        //构建前端所需要的返回参数
        List<ChatDto1> newRecords = new ArrayList<>();

        for (Chat record : list) {
            ChatDto1 chatDto1 = new ChatDto1();
            chatDto1.setId(record.getId());
            chatDto1.setSendtime(record.getSendtime());
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserid,record.getSendid());
            User sendUser = userService.getOne(queryWrapper);
            chatDto1.setUser(sendUser);
            chatDto1.setMessage(record.getMessage());
            newRecords.add(chatDto1);
        }


        return R.success(newRecords);
    }



    @RequestMapping ("/chat/send")
    public R<String> send(@RequestBody Map msg, HttpServletRequest request){
        String token = request.getHeader("Sessionid");
        User user = jwtUtil.getToken(token);
        System.out.println(1111);
        System.out.println(msg);

        return R.success("newRecords");
    }

}
